using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Services;
using Identity.Application.Roles.Commands;
using Identity.Domain.Aggregates;
using MediatR;

namespace Identity.Application.Roles.CommandHandlers
{
    public class UpdateRoleNameCommandHandler : IRequestHandler<UpdateRoleNameCommand, Result>
    {
        private IRoleService _roleService;

        public UpdateRoleNameCommandHandler(IRoleService roleService)
        {
            _roleService = roleService;
        }
        public async Task<Result> Handle(UpdateRoleNameCommand request, CancellationToken cancellationToken)
        {
            var roleData = await _roleService.GetRoleByIdAsync(request.RoleId);

            if (roleData == null) return Result.Failure("角色不存在");

            var role = Role.LoadFromPersistence(roleData.Id,roleData.Code, roleData.Name,roleData.PermissionIds,roleData.Description,roleData.Status);

            role.ChangeName(request.newRoleName);


            var result = await _roleService.UpdateRoleNameAsync(roleData.Id, request.newRoleName);
            if (!result.Succeeded) Result.Failure("角色名更新失败");

            return Result.Success();

        }
    }
}